package com.dcy.znoa.service.sys.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import com.dcy.znoa.controller.sys.model.storeFile.AddCommonModel;
import com.dcy.znoa.controller.sys.model.storeFile.AddStoreFileModel;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.dcy.znoa.common.util.pojo.JsonCommon;
import com.dcy.znoa.common.util.pojo.JsonForList;
import com.dcy.znoa.controller.publiz.model.SelectBaseModel;
import com.dcy.znoa.controller.sys.model.storeFile.SelectStoreFileModel;
import com.dcy.znoa.dao.sys.StoreFileDao;
import com.dcy.znoa.domain.sys.StoreFile;
import com.dcy.znoa.service.sys.StoreFileService;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import static com.dcy.znoa.common.util.pojo.JsonCommon.SUCCESS_CODE;

@Service
public class StoreFileServiceImpl implements StoreFileService {

    @Value(value = "${qiniuAccessKey}")
    String ACCESS_KEY;
    @Value(value = "${qiniuSecretKey}")
    String SECRET_KEY;
    @Value(value = "${qiniuDomain}")
    String DOMAIN;
    @Value(value = "${qiniuBucketName}")
    String bucketname;

    @Autowired
    StoreFileDao storeFileDao;

    //构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(Zone.zone2());

    // 密钥配置
    Auth auth;
    // 创建上传对象
    UploadManager uploadManager = new UploadManager(cfg);
    // 实例化一个BucketManager对象
    BucketManager bucketManager;
    // 简单上传，使用默认策略，只需要设置上传的空间名就可以了

    // 获取上传Token
    @Override
    public String getUpToken() {
        auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(bucketname);
        return upToken;
    }

    // 上传到七牛云服务空间
    @Override
    public boolean uploadFile(String filePath, String key) {

        try {
            // 调用put方法上传
            Response res = uploadManager.put(filePath, key, getUpToken());
            // 打印返回的信息
            System.out.println(res.bodyString());
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());

            try {
                // 响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                // ignore
                return false;
            }

            return false;
        }

        return true;
    }

    // 删除七牛云服务空间的文件
    @Override
    public boolean deleteFile(String key) {
        try {
            auth = Auth.create(ACCESS_KEY, SECRET_KEY);
            bucketManager = new BucketManager(auth, cfg);
            // 调用delete方法移动文件
            bucketManager.delete(bucketname, key);
        } catch (QiniuException e) {
            // 捕获异常信息
            Response r = e.response;
            System.out.println(r.toString());
            try {
                // 响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                // ignore
                return false;
            }

            return false;
        }
        return true;
    }

    // 获取该文件七牛云的下载路径
    @Override
    public String downloadFile(String key) {
        String url = DOMAIN + key;
        return url;

        //原私有访问模式，需要添加token
        /*
		auth = Auth.create(ACCESS_KEY, SECRET_KEY);
		// 调用privateDownloadUrl方法生成下载链接,第二个参数可以设置Token的过期时间
		String URL = DOMAIN + key;
		String downloadRUL = auth.privateDownloadUrl(URL, 3600);
		// System.out.println(downloadRUL);
		return downloadRUL;
		*/
    }

    @Override
    public JsonForList selectList(SelectStoreFileModel model) throws InvocationTargetException, IllegalAccessException {
        List<StoreFile> list;

        EntityWrapper<StoreFile> ew = new EntityWrapper<>();

        // 1 分页方法1，需要model继承 SelectBaseModel
        SelectBaseModel.PageFill(model, ew);// 加入分页参数
        list = storeFileDao.selectList(ew);
        // 2 分页方法2 ，需要model里面包含 RowBounds 类，查询调用分页方法,但是 RowBounds里面的参数是MySQL
        // 对应的，有点反人类，第一页要从0开始。
        // list = companyDao.selectPage(model.getRowBounds(),ew);
        if (list.isEmpty()) {
            return new JsonForList(null, SUCCESS_CODE, JsonCommon.SUCCESS_MSG);
        }
        return new JsonForList(list, SUCCESS_CODE, JsonCommon.SUCCESS_MSG);
    }

    @Override
    public JsonCommon insert(StoreFile storeFile) {
        if (StringUtils.isBlank(storeFile.getRemoteFileName())) {
            return new JsonCommon(JsonCommon.INSERT_ERROR_CODE, "remoteFileName不允许为空");
        }
        Integer result = storeFileDao.insert(storeFile);
        if (result == null || result <= 0) {
            return new JsonCommon(JsonCommon.INSERT_ERROR_CODE);
        }
        return new JsonCommon(SUCCESS_CODE, JsonCommon.SUCCESS_MSG);
    }

    @Override
    public JsonCommon updateByEntityId(Long entityId, String entityTbl) {

        StoreFile storeFile = new StoreFile();
        storeFile.setValidFlag(0);

        EntityWrapper<StoreFile> ew = new EntityWrapper<>();
        ew.eq("entity_id", entityId).eq("entity_tbl", entityTbl);

        Integer result = storeFileDao.update(storeFile, ew);
        if (result == null || result <= 0) {
            return new JsonCommon(JsonCommon.UPDATE_ERROR_CODE);
        }
        return new JsonCommon(SUCCESS_CODE, JsonCommon.SUCCESS_MSG);
    }

    @Override
    public List<StoreFile> selectStoreFileByEntityId(Long entityId, String entityTbl, String[] remoteFileName) {
        List<StoreFile> list;

        EntityWrapper<StoreFile> ew = new EntityWrapper<>();
        ew.eq("entity_id", entityId).eq("entity_tbl", entityTbl).eq("valid_flag", 1);
        if (remoteFileName != null && remoteFileName.length > 0) {
            ew.in("remote_file_name", remoteFileName);
        }

        list = storeFileDao.selectList(ew);

        return list;
    }

    @Override
    public void batchInsert(List<StoreFile> list) {
        for (StoreFile storeFile : list) {
            storeFileDao.insert(storeFile);
        }

    }

    @Override
    public JsonCommon updateById(StoreFile storeFile) {
        Integer result = storeFileDao.updateById(storeFile);
        if (result == null || result <= 0) {
            return new JsonCommon(JsonCommon.UPDATE_ERROR_CODE);
        }
        return new JsonCommon(SUCCESS_CODE, JsonCommon.SUCCESS_MSG);
    }

    @Override
    public void updateByEntityId(Long entityId, String entityTbl, String delFileName) {
        StoreFile storeFile = new StoreFile();
        storeFile.setValidFlag(0);

        EntityWrapper<StoreFile> ew = new EntityWrapper<>();
        ew.eq("entity_id", entityId).eq("entity_tbl", entityTbl).eq("remote_file_name", delFileName);

        storeFileDao.update(storeFile, ew);

    }

    @Override
    public Integer addBatch(AddStoreFileModel addStoreFileModel) throws InvocationTargetException, IllegalAccessException {
        if (addStoreFileModel.getRemoteFileName() != null) {
            String[] fileNames = addStoreFileModel.getRemoteFileName().split(",");
            for (String remoteFileName : fileNames) {
                StoreFile storeFile = new StoreFile();
                BeanUtils.copyProperties(storeFile, addStoreFileModel);
                storeFile.setRemoteFileName(remoteFileName);
                storeFile.setFileName(remoteFileName);//三个名字都一样
                storeFile.setDownloadPath(remoteFileName);//三个名字都一样
                Integer result = storeFileDao.insert(storeFile);
                if (result <= 0) {
                    return 0;
                }
            }
            return 1;
        }
        return 0;
    }


}
